//
//  BrowserTopToolBar.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2016/10/12.
//  Copyright © 2021年 梁慧聪. All rights reserved.
//

#import "CLWebTopBar.h"
#import "CLTopBarView.h"

#import "CLWebViewProgressView.h"
#import "CLDelegateManager+WebViewDelegate.h"
#import "CLWebViewManager.h"

#define SHAPE_VIEW_WIDTH 30
#define SHAPE_VIEW_HEIGHT 44
#define SHAPE_VIEW_Y_OFFSET 5

@interface CLWebTopBar () <CLWebViewDelegate>

@property (nonatomic, strong) CLTopBarView *shapeView;
@property (nonatomic, strong) CLWebViewProgressView *progressView;
@property (nonatomic, strong) CLWebViewProgress *progressProxy;
@property (nonatomic, strong) UIButton *expandButton;
@property (nonatomic, strong) UIView *line;
@end

@implementation CLWebTopBar

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self initializeView];
        [[CLDelegateManager sharedInstance] registerDelegate:self forKey:kDelegateManagerWebView];
        [[CLDelegateManager sharedInstance] addWebViewDelegate:self];
        [Notifier addObserver:self selector:@selector(handletabSwitch:) name:kWebTabSwitch object:nil];
    }
    return self;
}

- (void)initializeView {
    if (@available(iOS 13.0, *)) {
        UIColor *backgroundColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            return [traitCollection userInterfaceStyle] == UIUserInterfaceStyleDark ? UIColorFromRGB(0x3C3C3C) : UIColorFromRGB(0xF8F8F8);
        }];
        self.backgroundColor = backgroundColor;
    }
    self.shapeView = ({
        CLTopBarView *shapeView = [[CLTopBarView alloc] initWithFrame:CGRectMake(0, 0, self.width - SHAPE_VIEW_WIDTH, self.height - SHAPE_VIEW_HEIGHT)];
        shapeView.center = (CGPoint){CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds) + SHAPE_VIEW_Y_OFFSET};
        shapeView.shapeLayer.lineWidth = 2;
        if (@available(iOS 13.0, *)) {
            UIColor *fillColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
                return [traitCollection userInterfaceStyle] == UIUserInterfaceStyleDark ? [UIColor blackColor] : UIColorFromRGB(0xE6E6E7);
            }];
            shapeView.shapeLayer.fillColor = fillColor.CGColor;
        }
        
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:shapeView.bounds cornerRadius:6];
        shapeView.shapeLayer.path = path.CGPath;
        
        [self addSubview:shapeView];
        shapeView;
    });
    
    self.expandButton = ({
        UIButton *expandButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self addSubview:expandButton];
        
        expandButton.frame = CGRectMake(0, 0, 18, 18);
        expandButton.hidden = YES;
        [expandButton addTarget:self action:@selector(handleExpandBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [expandButton setImage:[UIImage imageNamed:@"toolbar_expand_normal"] forState:UIControlStateNormal];
        
        expandButton;
    });
    
    self.progressView = ({
        CGFloat progressBarHeight = 2.f;
        CLWebViewProgressView *progressView = [[CLWebViewProgressView alloc] initWithFrame:CGRectMake(0, self.height - progressBarHeight, self.width, progressBarHeight)];
        [self addSubview:progressView];
        
        progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
        
        progressView;
    });
    
    self.progressProxy = ({
        CLWebViewProgress *progressProxy = [CLWebViewProgress new];
        
        progressProxy.progressDelegate = self;
        
        progressProxy;
    });
    
  self.line = [self cl_addBottomSeparatorLineWithColor:[UIColor colorWithWhite:0.0 alpha:0.5] height:0.5];
}

- (void)setFrame:(CGRect)frame{
    if (frame.size.height != self.height) {
        CGFloat shapeViewHeight = fabs(frame.size.height * (TOP_TOOL_BAR_HEIGHT - SHAPE_VIEW_HEIGHT) / TOP_TOOL_BAR_HEIGHT);
        self.shapeView.center = (CGPoint){frame.size.width/2, frame.size.height/2 + SHAPE_VIEW_Y_OFFSET};
        
        self.shapeView.transform = CGAffineTransformMakeScale(shapeViewHeight / (TOP_TOOL_BAR_HEIGHT - SHAPE_VIEW_HEIGHT), shapeViewHeight / (TOP_TOOL_BAR_HEIGHT - SHAPE_VIEW_HEIGHT));
        self.expandButton.center = CGPointMake(frame.size.width - 30, frame.size.height / 2 + SHAPE_VIEW_Y_OFFSET);
    }
    self.expandButton.hidden = (frame.size.height != TOP_TOOL_BAR_THRESHOLD);
    
    [super setFrame:frame];
    
    self.line.bottom = CGRectGetHeight(frame);
}

- (void)setTopURLOrTitle:(NSString *)urlOrTitle{
    [self.shapeView setTopURLOrTitle:urlOrTitle];
}

#pragma mark - CLWebViewDelegate

- (void)webView:(CLWebView *)webView gotTitleName:(NSString *)titleName{
    if (IsCurrentWebView(webView)) {
        [self setTopURLOrTitle:titleName];
    }
}

- (BOOL)webView:(CLWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if (IsCurrentWebView(webView) && [self.progressProxy respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) {
        return [self.progressProxy webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
    }

    return YES;
}
- (BOOL)webView:(CLWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    if (IsCurrentWebView(webView) && [self.progressProxy respondsToSelector:@selector(webView:decidePolicyForNavigationAction:decisionHandler:)]) {
        return [self.progressProxy webView:webView decidePolicyForNavigationAction:navigationAction decisionHandler:decisionHandler];
    }

    return YES;
}
- (void)webViewDidFinishLoad:(CLWebView *)webView{
    if (IsCurrentWebView(webView) && [self.progressProxy respondsToSelector:@selector(webViewDidFinishLoad:)]) {
        [self.progressProxy webViewDidFinishLoad:webView];
    }
}

- (void)webViewDidStartLoad:(CLWebView *)webView{
    if (IsCurrentWebView(webView) && [self.progressProxy respondsToSelector:@selector(webViewDidStartLoad:)]) {
        [self.progressProxy webViewDidFinishLoad:webView];
    }
}

- (void)webView:(CLWebView *)webView didFailLoadWithError:(NSError *)error{
    if (IsCurrentWebView(webView) && [self.progressProxy respondsToSelector:@selector(webView:didFailLoadWithError:)]) {
        [self.progressProxy webView:webView didFailLoadWithError:error];
    }
}

- (void)webView:(CLWebView *)webView hiddenTopBar:(BOOL)isHiddenTopBar {
    if (IsCurrentWebView(webView)) {
        self.hidden = isHiddenTopBar;
    } else {
        self.hidden = NO;
    }
}
#pragma mark - Expand Button Handler

- (void)handleExpandBtnClicked:(UIButton *)btn{
    [Notifier postNotification:[NSNotification notificationWithName:kExpandHomeToolBarNotification object:nil]];
}

#pragma mark - CLWebViewProgressDelegate

-(void)webViewProgress:(CLWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_progressView setProgress:progress animated:YES];
}

#pragma mark - kWebTabSwitch notification handler

- (void)handletabSwitch:(NSNotification *)notification{
    CLWebView *webView = [notification.userInfo objectForKey:@"webView"];
    if ([webView isKindOfClass:[CLWebView class]]) {
        NSString *title = [webView mainFTitle];
        [self setTopURLOrTitle:title];
    }
}

#pragma mark - Dealloc

- (void)dealloc{
    [Notifier removeObserver:self name:kWebTabSwitch object:nil];
}

- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    if (@available(iOS 13.0, *)) {
        if ([self.traitCollection hasDifferentColorAppearanceComparedToTraitCollection:previousTraitCollection]) {
            UIColor *backgroundColor = [ UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
                return [traitCollection userInterfaceStyle] == UIUserInterfaceStyleDark ? UIColorFromRGB(0x3C3C3C) : UIColorFromRGB(0xF8F8F8);
            }];
            self.backgroundColor = backgroundColor;
        }
        UIColor *fillColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            return [traitCollection userInterfaceStyle] == UIUserInterfaceStyleDark ? [UIColor blackColor] : UIColorFromRGB(0xE6E6E7);
        }];
        self.shapeView.shapeLayer.fillColor = fillColor.CGColor;
    }

    
}
@end
